package com.str.demo02;

import com.sun.deploy.util.StringUtils;

import java.util.Arrays;
import java.util.StringJoiner;

public class Test02 {
    public static void main(String[] args) {
        String[] names = {"Bob", "Alice", "Grace"};
        StringBuilder sb = new StringBuilder();
        sb.append("Hello ");
        for (String name : names) {
            sb.append(name).append(", ");
        }
        // 注意去掉最后的", ":
        sb.delete(sb.length() - 2, sb.length());
        sb.append("!");
        System.out.println(sb.toString());
        System.out.println("==========");
        joins();
        System.out.println("===========");
        real();
    }

    // StringJoiner 数组分割成为字符串
    public static void joins() {
        // 使用符号分割数组
        String[] names = {"one","two","three"};
        StringJoiner stringJoiner = new StringJoiner("，");
        for (String s : names) {
            stringJoiner.add(s);
        }
        System.out.println(stringJoiner); // one，two，three
        // 可以指定开头 和 结尾的字符串分割符
        StringJoiner sj = new StringJoiner(":", "[", "]");
        sj.add("jack").add("kerry").add("jam");
        System.out.println(sj); // [jack:kerry:jam]
    }

    /**
     * StringJoiner 用法
     * 作用是在构造字符串时，可以自动添加前缀、后缀及分隔符，而不需要自己去实现这些添加字符的逻辑
     * 简单来说：对于特殊字符的拼接 简单化操作
     */
    public static void real() {
        // 例如 一个数组 {"one","two","three"}; ，转化成为 ，逗号拼接 one，two，three
        String[] names = {"one","two","three"};
        StringBuilder stringBuilder = new StringBuilder();
        for (String name : names) {
            stringBuilder.append(name).append(",");
        }
        // 还需要除后面的逗号 delete 左闭右开
        stringBuilder.delete(stringBuilder.length() - 1,stringBuilder.length());
        System.out.println(stringBuilder); // one,two,three
        System.out.println("==========");
        // 换成  StringJoiner(分割符号，开头链接符，结束符号) 处理方法
        StringJoiner stringJoiner = new StringJoiner(",");
        for (String s : names) {
            stringJoiner.add(s);
        }
        System.out.println(stringJoiner); // one,two,three
        System.out.println("======拼接复杂的字符串=====");
        // [jack:kerry:jam]
        StringJoiner sj = new StringJoiner(":", "[", "]");
        sj.add("jack").add("kerry").add("jam");
        System.out.println(sj); // [jack:kerry:jam]
        // 又或者
        String[] k = {"java","is","best","lang"};
        StringJoiner str = new StringJoiner(" ","[","]");
        for (String s : k) {
            str.add(s);
        }
        System.out.println(str);
        System.out.println("===== join 方法=====");
        // 还有一种方法 将数组转化为字符串 StringUtils.join()
        String[] arr = {"Bob", "Alice", "Grace"};
        String str3 = String.join(",", arr);
        System.out.println(str3);
    }
}
